package com.lucas.rpc.framework.transport.tomcat;

import com.lucas.rpc.framework.register.LocalRegister;
import com.lucas.rpc.framework.remote.RpcRequest;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

/**
 * @author: LiuCheng
 * @description:
 * @date: 2023-11-27 17:28
 **/
public class HttpServerHandler {

    public void handle(HttpServletRequest req, HttpServletResponse resp){
        try {
            RpcRequest rpcRequest = (RpcRequest)new ObjectInputStream(req.getInputStream()).readObject();

            String interfaceName = rpcRequest.getInterfaceName();

            String version = rpcRequest.getVersion();

            if(null==version||"".equals(version)){
                version = "1.0";
            }

            Class implClass = LocalRegister.getImplClass(interfaceName, version);

            Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());

            String result = (String)method.invoke(implClass.newInstance(), rpcRequest.getParameters());
            IOUtils.write(result,resp.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
